<template>
    <div class="main_container">
        <el-row style="height: 40px;line-height: 40px;margin: 10px 20px 25px 20px;">
            <el-col :span="5">
                <el-radio-group v-model="filterType" @change="radioChange">
                    <el-radio label="1">按条件筛选</el-radio>
                    <el-radio label="2">按日期范围</el-radio>
                </el-radio-group>
            </el-col>
            <el-col :span="6" v-if="filterType=='1'">
                <el-select style="width: 240px;" v-model="order_type" placeholder="请选择"
                    @change="typeChange" clearable>
                    <el-option v-for="item in filterTypes" :key="'filter_'+item.value" 
                        :label="item.label" :value="item.value"></el-option>
                </el-select>
            </el-col>
            <el-col :span="6" v-else>
                <el-date-picker type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" 
                    v-model="dateRange" format="yyyy-MM-dd" value-format="yyyy-MM-dd" 
                    :picker-options="handleTime" @change="dateChange"
                    placeholder="请选择日期范围" style="width: 240px;" clearable></el-date-picker>
            </el-col>
            <el-col :span="7">
                <div style="display: flex;align-items: center;" @click="showMore=!showMore">
                    <span style="font-size: 14px;color: #606266;width: auto;cursor: pointer;margin-right: 5px;">高级搜索</span>
                    <i :class="showMore?'el-icon-arrow-up':'el-icon-arrow-down'"></i>
                </div>
            </el-col>
            <el-col :span="6">
                <div class="btns">
                    <!-- <el-button size="small" style="margin-right: 10px;" icon="el-icon-upload2" @click="handleExport">导出</el-button> -->
                    <!-- <el-button size="small" class="btn_primary_color" icon="el-icon-printer" @click="handlePrint">打印</el-button> -->
                </div>
            </el-col>
        </el-row>
        <el-row v-if="showMore" style="height: 40px;line-height: 40px;margin: 10px 20px 25px 20px;">
            <el-col :span="7" style="display: flex;align-items: center;">
                <span style="font-size: 14px;color: #606266;width: auto;">客户名称：</span>
                <div class="choose_border" @click="showChooseCustomerAlert = true">
                    <span style="color: #c0c4cf;" v-if="!cusInfo.customer_name">请选择</span>
                    <span>{{ cusInfo.customer_name }}</span>
                    <i class="el-icon-circle-close icon" @click.stop="clearValue('customer')"></i>
                </div>
            </el-col>
            <el-col :span="7" style="display: flex;align-items: center;">
                <span style="font-size: 14px;color: #606266;width: auto;">经办人：</span>
                <div class="choose_border" @click="showChooseUserAlert=true">
                    <span style="color: #c0c4cf;" v-if="!cusInfo.handler_name">请选择</span>
                    <span>{{ cusInfo.handler_name }}</span>
                    <i class="el-icon-circle-close icon" @click.stop="clearValue('handler')"></i>
                </div>
            </el-col>
        </el-row>

        <div class="common_line"></div>
        <el-row style="padding: 5px 14%;">
            <el-col :span="6" class="flex_div">
                <span class="top_title">销售额</span>
                <span class="money" :class="totalData.turnover<0?'red':'green'">{{ totalData.turnover.toFixed(2) }}</span>
            </el-col>
            <el-col :span="6" class="flex_div">
                <span class="top_title">总数量</span>
                <span class="money order" :class="totalData.orderCount<0?'red':'green'">{{ totalData.orderCount }}</span>
            </el-col>
            <el-col :span="6" class="flex_div">
                <span class="top_title">毛利润</span>
                <span class="money" :class="totalData.profit<0?'red':'green'">{{ totalData.profit.toFixed(2) }}</span>
            </el-col>
            <el-col :span="6" class="flex_div">
                <span class="top_title">毛利率</span>
                <span style="font-size: 22px;font-weight: bold;" :class="totalData.total_gross_profit<0?'red':'green'">{{ totalData.total_gross_profit.toFixed(2)+'%' }}</span>
            </el-col>
        </el-row>
        <div class="common_line"></div>
        <el-table border :data="tableData" v-loading="loading" show-summary :summary-method="getSummaries"
            :max-height="tableHeight" style="margin-top: 15px;">
            <!-- <el-table-column label="客户" align="center" show-overflow-tooltip >
                <template slot-scope="scope">
                    <span class="customer_name" @click="handleSingleData(scope.row)">{{ scope.row.title }}</span>
                </template>
            </el-table-column> -->
            <el-table-column label="客户" align="center" prop="title" />
            <el-table-column label="总数量" align="center" prop="goods_total_num" />
            <el-table-column label="销售数量" align="center" prop="sales_goods_total_num" />
            <el-table-column label="退货数量" align="center" prop="return_goods_total_num" />
            <el-table-column label="销售额" align="center" prop="turnover_name" />
            <el-table-column label="利润" align="center" prop="profit_name" />
            <!-- <el-table-column label="已收款" align="center" prop="paid_payment_name" />
            <el-table-column label="未收款" align="center" prop="pending_payment_name" /> -->
            <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        @click="handlePrint(scope.row)"
                        style="font-weight: bold;"
                    >打印对账单</el-button>
                </template>
            </el-table-column> -->
        </el-table>
        <el-pagination
            v-show="total>0"
            background
            style="padding: 32px 16px;background: #fff;text-align: right;"
            @size-change="handleSizeChange"
            @current-change="getNextPageList"
            :current-page.sync="pageParam.page"
            :page-size="pageParam.num"
            layout="total, prev, pager, next, sizes, jumper"
            :page-sizes="[10, 20, 50, 100]"
            :total="total">
        </el-pagination>

        <el-dialog :title="diglogTitle" :close-on-click-modal="false" :visible.sync="showInfo" width="60%" center append-to-body>
            <div style="max-height: 420px;overflow-y: auto;">
                <el-row>
                    <el-radio-group v-model="singleParams.order_type" @change="singleRadioChange">
                        <el-radio label="month">月度</el-radio>
                        <el-radio label="quarter">季度</el-radio>
                    </el-radio-group>
                </el-row>
                <div class="common_line"></div>
                <el-row style="padding: 5px 14%;">
                    <el-col :span="6" class="flex_div">
                        <span class="top_title">营业额</span>
                        <span class="money" :class="singleTotalData.turnover<0?'red':'green'">{{ singleTotalData.turnover.toFixed(2) }}</span>
                    </el-col>
                    <el-col :span="6" class="flex_div">
                        <span class="top_title">总数量</span>
                        <span class="money order" :class="singleTotalData.orderCount<0?'red':'green'">{{ singleTotalData.orderCount }}</span>
                    </el-col>
                    <el-col :span="6" class="flex_div">
                        <span class="top_title">毛利润</span>
                        <span class="money" :class="singleTotalData.profit<0?'red':'green'">{{ singleTotalData.profit.toFixed(2) }}</span>
                    </el-col>
                    <el-col :span="6" class="flex_div">
                        <span class="top_title">毛利率</span>
                        <span class="money" :class="singleTotalData.total_gross_profit<0?'red':'green'">{{ singleTotalData.total_gross_profit.toFixed(2)+'%' }}</span>
                    </el-col>
                </el-row>
                <div class="common_line"></div>
                <el-table border :data="singleData" style="margin-top: 15px;">
                    <el-table-column label="时间" align="center" prop="title" />
                    <el-table-column label="销售数量" align="center" prop="sales_count" />
                    <!-- <el-table-column label="退货数量" align="center" prop="return_count" /> -->
                    <el-table-column label="销售额" align="center" prop="turnover_name" />
                    <el-table-column label="利润" align="center" prop="profit_name" />
                    <!-- <el-table-column label="已收款" align="center" prop="paid_payment" />
                    <el-table-column label="未收款" align="center" prop="pending_payment" /> -->
                </el-table>
            </div>
        </el-dialog>
        <!-- 选择客户 -->
        <choose-customer
            :showChooseCustomer="showChooseCustomerAlert"
            :selectUsers="customerList"
            @chooseOK="chooseCustomerOK"
            @hidden="showChooseCustomerAlert=false"
        ></choose-customer>

        <!-- 选择经办人 -->
        <choose-user
            :showChooseUser="showChooseUserAlert"
            :selectUsers="handlersList"
            title="选择经办人"
            @chooseOK="chooseUserOK"
            @hidden="showChooseUserAlert=false"
        ></choose-user>
    </div>
</template>

<script>
import { getCustomerList } from "@/api/cooperate";
import { getUserList } from "@/api/user";
import { customBang, customBangSingle } from '@/api/statistics'
import { urlToPdf } from '@/api/common';
import { getToken } from '@/utils/auth';
import chooseCustomer from "@/components/chooseCustomer";
import chooseUser from "@/components/chooseUser";

export default {
    name: 'customerSales',
    components: {
        chooseCustomer,
        chooseUser,
    },
    data() {
        return {
            showMore: false,
            showInfo: false,
            showLoading: false,
            loading: false,
            showChooseCustomerAlert: false,
            showChooseUserAlert: false,
            filterType: '1',  //1 按条件  2 按日期范围
            filterTypes: [
                {id: 1, label: '日榜', value: 'cur_day'},
                {id: 2, label: '周榜', value: 'cur_weak'},
                {id: 3, label: '月度榜', value: 'cur_month'},
                {id: 4, label: '季度榜', value: 'cur_quarter'},
                {id: 5, label: '年度榜', value: 'cur_year'},
            ],
            params: {
                corp_id: '',
                start_date: '',
                end_date: '',
                order_by: "turnover",
                order_type: 'cur_month',
                customer_id: '',
                handler_user_id: ''
            },
            pageParam: {
                page: 1,
                num: 10
            },
            total: 0,
            tableHeight: 420,
            totalLists: [],
            printParam: {
                start_date: '',
                end_date: '',
            },
            order_type: 'cur_month',
            dateRange: [],
            handleTime: {
                disabledDate(date) {
                    //disabledDate 文档上：设置禁用状态，参数为当前日期，要求返回 Boolean
                    return date.getTime() > Date.now();
                }
            },
            totalData: {
                orderCount: 0,  //开单数量
                turnover: 0,  //营业额
                profit: 0,  //利润
                total_gross_profit: 0  //毛利率
            },
            tableData: [],
            cusInfo: {
                customer_name: '',
                handler_name: ''
            },
            customerList: [],
            handlersList: [],
            diglogTitle: '',
            singleParams: {
                corp_id: '',
                start_date: '',
                order_type: 'month',
                customer_id: ''
            },
            singleData: [],
            singleTotalData: {
                orderCount: 0,  //开单数量
                turnover: 0,  //营业额
                profit: 0,  //利润  
                total_gross_profit: 0  //毛利率
            }
        }
    },
    created() {
        if (window.innerHeight > 1000) {
            this.tableHeight = window.innerHeight - 400
        }
        this.params.corp_id = this.$store.state.corpId
        this.singleParams.corp_id = this.$store.state.corpId
        let nowDate = new Date()
        this.params.start_date = nowDate.getFullYear()+'-'+this.add0(nowDate.getMonth()+1)+'-01'
        this.printParam.start_date = this.params.start_date
        this.printParam.end_date = nowDate.getFullYear()+'-'+this.add0(nowDate.getMonth()+1)+'-'+this.add0(nowDate.getDate())
        this.getData()
    },
    methods: {
        // 补零
        add0(num) {
            if (parseInt(num) < 10){
                num = '0'+ num
            }
            return num
        },
        clearValue(type) {
            if (type == 'customer'){
                this.params.customer_id = ''
                this.cusInfo.customer_name = ''
            }else {
                this.params.handler_user_id = ''
                this.cusInfo.handler_name = ''
            }
            this.getData()
        },
        chooseCustomerOK(res) {
            this.params.customer_id = res.length ? res[0].id : ''
            this.cusInfo.customer_name = res.length ? res[0].name : ''
            this.getData()
            this.showChooseCustomerAlert = false
        },
        chooseUserOK(res) {
            this.params.handler_user_id = res.length ? res[0].id : ''
            this.cusInfo.handler_name = res.length ? res[0].username : ''
            this.getData()
            this.showChooseUserAlert = false
        },
         getSummaries(param) {
            const { columns, data } = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '合计';
                    return;
                }
                const values = data.map(item => Number(item[column.property]));
                if (!values.every(value => isNaN(value))) {
                    sums[index] = values.reduce((prev, curr) => {
                    const value = Number(curr);
                    if (!isNaN(value)) {
                        return prev + curr;
                    } else {
                        return prev;
                    }
                    }, 0);
                    sums[index] = sums[index].toFixed(2);
                } else {
                    sums[index] = '--';
                }
            });

            return sums;
        },
        // 获取数据
        getData() {
            var that = this
            that.loading = true
            customBang(this.params).then(res => {
                that.totalData = {
                    orderCount: 0,  //开单数量
                    turnover: 0,  //营业额
                    profit: 0  //利润
                }

                let lists = res.data.data.filter(item => {
                    item.title = item.name
                    item.turnover_name = item.turnover.toFixed(2)
                    item.profit_name = item.profit.toFixed(2)
                    // item.paid_payment_name = item.paid_payment.toFixed(2)
                    // item.pending_payment_name = item.pending_payment.toFixed(2)

                    that.totalData.orderCount = that.$common.plusFloat(that.totalData.orderCount, item.goods_total_num)
                    that.totalData.turnover = that.$common.plusFloat(that.totalData.turnover, item.turnover)
                    that.totalData.profit = that.$common.plusFloat(that.totalData.profit, item.profit)
                    return item
                })
                if (lists.length && that.totalData.turnover!=0){
                    that.totalData.total_gross_profit = that.$common.multiplyDivision(that.totalData.profit, that.totalData.turnover)*100
				}else{
                    that.totalData.total_gross_profit = 0
                }
                that.totalLists = lists
                that.total = lists.length
                that.pageParam.page = 1
                that.getNextPageList()
                that.loading = false
            })
        },
        handleSizeChange(val) {
            this.pageParam.num = val
            this.getNextPageList()
        },
        getNextPageList() {
            let totalPage = 0  //总页数
            if (this.total % this.pageParam.num === 0){  //整除
                totalPage = Math.trunc(this.total / this.pageParam.num)
            }else{
                totalPage = Math.trunc(this.total / this.pageParam.num) + 1
            }

            function chunkArray(arr, size) {
                const result = [];
                for (let i = 0; i < arr.length; i += size) {
                    result.push(arr.slice(i, i + size));
                }
                return result;
            }

            if (this.pageParam.page <= totalPage){
                let groups = chunkArray(this.totalLists, this.pageParam.num)
                this.tableData = groups[this.pageParam.page-1]
            }else{
                this.tableData = []
            }
        },
        radioChange(val) {
            if (val == '1'){
                this.typeChange(this.order_type)
            }else{
                this.dateChange(this.dateRange)
            }
        },
        typeChange(val) {
            if (!val) return

            console.log(val)
            let nowDate = new Date()
            this.params.start_date = ''
            if(val == 'cur_quarter'){  //季度
                let curQuarter = this.getCurrentQuarter()
                switch (curQuarter){
                    case 1:
                        this.params.start_date = nowDate.getFullYear()+'-01-01'
                        this.printParam.end_date = nowDate.getFullYear()+'-03-31'
                        break;
                    case 2:
                        this.params.start_date = nowDate.getFullYear()+'-04-01'
                        this.printParam.end_date = nowDate.getFullYear()+'-06-30'
                        break;
                    case 3:
                        this.params.start_date = nowDate.getFullYear()+'-07-01'
                        this.printParam.end_date = nowDate.getFullYear()+'-09-30'
                        break;
                    case 4:
                        this.params.start_date = nowDate.getFullYear()+'-10-01'
                        this.printParam.end_date = nowDate.getFullYear()+'-12-31'
                        break;
                    default:
                        break;
                }
                this.printParam.start_date = this.params.start_date
            }else if(val == 'cur_month'){  //月度
                this.params.start_date = nowDate.getFullYear()+'-'+this.add0(nowDate.getMonth()+1)+'-01'
                this.printParam.start_date = this.params.start_date
                this.printParam.end_date = nowDate.getFullYear()+'-'+this.add0(nowDate.getMonth()+1)+'-'+this.add0(nowDate.getDate())
            }else if (val == 'cur_year'){  //年度
                this.printParam.start_date = nowDate.getFullYear()+'-01-01'
                this.printParam.end_date = nowDate.getFullYear()+'-12-31'
            }else if (val == 'cur_weak'){  //周榜
                const dayOfWeek = nowDate.getDay();
                const daysUntilMonday = (dayOfWeek === 0 ? -6 : 1 - dayOfWeek);
                const monday = new Date(nowDate);
                monday.setDate(nowDate.getDate() + daysUntilMonday);

                this.printParam.start_date = monday.getFullYear()+'-'+this.add0(monday.getMonth()+1)+'-'+this.add0(monday.getDate())
                this.printParam.end_date = nowDate.getFullYear()+'-'+this.add0(nowDate.getMonth()+1)+'-'+this.add0(nowDate.getDate())
            }else if (val == 'cur_day'){  //日榜
                this.printParam.start_date = nowDate.getFullYear()+'-'+this.add0(nowDate.getMonth()+1)+'-'+this.add0(nowDate.getDate())
                this.printParam.end_date = this.printParam.start_date
            }

            this.params.order_type = val

            this.getData()
        },
        // 获取当前是第几季度
        getCurrentQuarter() {
            let curMonth = new Date().getMonth() + 1
            let quarters = [[1,2,3], [4,5,6], [7,8,9], [10,11,12]]
            let curQuarter = 0
            quarters.forEach((item, index) => {
                if (item.includes(curMonth)){
                    curQuarter = index+1
                }
            })
            return curQuarter
        },
        dateChange(value) {
            if(value && value.length){
                this.params.start_date = value[0]
                this.params.end_date = value[1]
                this.params.order_type = 'customize_date'
                this.getData()
            }
            else{
                this.params.start_date = this.params.end_date = null
                this.params.order_type = ''
                this.tableData = []
                this.totalData = {
                    orderCount: 0,  //采购支出
                    turnover: 0,  //营业额
                    profit: 0,  //利润
                    total_gross_profit: 0
                }
            }
        },
        // 下钻
        handleSingleData(item) {
            console.log(item)
            this.diglogTitle = item.title+'贡献值'
            this.singleParams.customer_id = item.id
            this.singleParams.start_date = (new Date().getFullYear())+'-01-01'
            this.getCustomerInfo()
        },
        // 获取单个客户贡献值数据
        getCustomerInfo() {
            var that = this
            let nowDate = new Date()
            customBangSingle(this.singleParams).then(res => {
                let curYear = nowDate.getFullYear(),
                    curMonth = nowDate.getMonth()+1;
                let quarters = [[1,2,3], [4,5,6], [7,8,9], [10,11,12]]
                let curQuarter = 0
                quarters.forEach((item, index) => {
                    if (item.includes(curMonth)){
                        curQuarter = index+1
                    }
                })

                that.singleTotalData = {
                    orderCount: 0,  //开单数量
                    turnover: 0,  //营业额
                    profit: 0  //利润
                }
                let lists = res.data.data.filter(item => {
                    if (that.singleParams.order_type == 'month') {
                        item.title = item.y_m_d + '月'
                    }else if (that.singleParams.order_type == 'quarter') {
                        item.title = '第' + item.y_m_d + '季度'
                    }
                    item.turnover_name = item.turnover.toFixed(2)
                    item.profit_name = item.profit.toFixed(2)
                    that.singleTotalData.orderCount = that.$common.plusFloat(that.singleTotalData.orderCount, item.sales_count)
                    that.singleTotalData.turnover = that.$common.plusFloat(that.singleTotalData.turnover, item.turnover)
                    that.singleTotalData.profit = that.$common.plusFloat(that.singleTotalData.profit, item.profit)
                    return item
                })
                that.singleData = lists
                that.showInfo = true
            })
        },
        singleRadioChange() {
            this.getCustomerInfo()
        },
        // 导出
        handleExport() {

        },
        // 打印
        handlePrint(item) {
            if (this.filterType == '2'){  //按日期范围
                this.printParam.start_date = this.params.start_date
                this.printParam.end_date = this.params.end_date
            }
            let param = {
                corp: this.params.corp_id,
                customer: item.id,
                begin: this.printParam.start_date,
                end: this.printParam.end_date
            }

            urlToPdf({
                corpId: this.params.corp_id,
                pdf_file_add: {
                    unique_order_no: '',
                    unique_type: 'pdf_customerBill',
                    show_filename: '客户对账单.pdf',
                    req_url: 'https://anhuiyaoying.com/pdf/customerBill.html?corp='+param.corp+
                        '&customer='+param.customer+'&begin='+param.begin+'&end='+param.end
                },
                print_dict: {
                    page_height: 29.7,
                    page_width: 21.0,
                    orientation: "portrait",
                },
                domain: 'anhuiyaoying.com',
                cookies_dict: {
                    Authorization_TOKEN: getToken()
                }
            }).then(res => {
                if (res.code == 200){
                    window.open(res.data.pdf_url)
                }else{
                    this.$message.error(res.message)
                }
            })
        },
        // 选择客户
        personChange(value) {
            if (value){
                let [ id, name ] = value.split('&&')
                this.params.customer_id = id
                this.cusInfo.customer_name = name
            }else{
                this.params.customer_id = ''
                this.cusInfo.customer_name = ''
            }
            this.getData()
        },
        remoteMethodWithCustomer(query) {
            if (query !== '') {
                this.showLoading = true
                getCustomerList({
                    corp: this.params.corp_id,
                    category: '',
                    search: query
                }).then(res => {
                    this.showLoading = false
                    this.customerList = res.data.data.customer_list.filter(item => {
                        item.label = item.name
                        item.value = item.id+'&&'+item.name
                        if (item.category_detail && item.category_detail.name){
                            item.label += ('（'+item.category_detail.name+'）')
                        }
                        return item
                    });
                })
            } else {
                this.customerList = []
            }
        },
        // 选择经办人
        handlerPersonChange(value) {
            if (value){
                let [ id, username ] = value.split('&&')
                this.params.handler_user_id = id
                this.cusInfo.handler_name = username
            }else{
                this.params.handler_user_id = ''
                this.cusInfo.handler_name = ''
            }
            this.getData()
        },
        remoteMethodWithHandler(query) {
            if (query !== '') {
                this.showLoading = true
                getUserList({
                    corp: this.params.corp_id,
                    username: query
                }).then(res => {
                    this.showLoading = false
                    this.handlersList = res.data.users.filter(item => {
                        item.label = item.username
                        item.value = item.id+'&&'+item.username
                        if (item.phone_no){
                            item.label += ('（'+item.phone_no+'）')
                        }
                        return item
                    });
                })
            } else {
                this.handlersList = []
            }
        },
    }
}
</script>

<style lang="less" scoped>
    @import '../../style/mixin.less';
    .btns {
        float: right;
        height: 40px;
        display: flex;
        align-items: center;
        padding-right: 20px;
    }
    .flex_div {
        display: flex;
        flex-direction: column;
        align-items: center;
        .top_title {
            font-size: 14px;
            color: #606266;
            margin-bottom: 14px;
        }
        .money {
            font-size: 22px;
            font-weight: bold;
            // color: red;
            &::before {
                content: '￥';
                font-size: 14px;
            }
        }
        .order {
            &::before {
                content: '';
            } 
        }
        .red {
            color: red;
        }
        .green {
            color: @blue;
        }
    }
    .customer_name {
        cursor: pointer;
        color: red;
    }
</style>